package com.joplus.housekeeper.adapter;

import android.content.Context;
import android.os.Handler;
import android.os.Message;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.hyphenate.util.DensityUtil;
import com.joplus.housekeeper.R;
import com.joplus.housekeeper.bean.EventSelectDetail.DataBean.EventPayDateilSessionDTOsBean.TypeListBean;
import com.joplus.housekeeper.bean.EventSelectDetail.DataBean.EventPayDateilSessionDTOsBean.TypeListBean.EventPriceBean;
import com.joplus.housekeeper.bean.TicketOrderDetail;
import com.joplus.housekeeper.utils.DecimalFormatTool;
import com.joplus.housekeeper.utils.L;
import com.joplus.housekeeper.utils.StringUtils;
import com.joplus.housekeeper.utils.T;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;

/**
 * Created by Administrator on 2016/6/29.
 */
public class TicketsAdapter extends BaseAdapter {


    Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case 0:
                    T.show(context, "数量不能在减啦", Toast.LENGTH_SHORT);
                    break;
            }

        }
    };

    List<TypeListBean> typeList;

    Map<Integer, TicketOrderDetail> ticketOrderDetailMap = new HashMap<>();


    LayoutInflater layoutInflater;
    OnPriceChanged onPriceChanged;
    String memberId = null;
    float money;
    Context context;
    Boolean isCanbeSelect = false;

    public TicketsAdapter(Context context, String memberId) {
        layoutInflater = LayoutInflater.from(context);
        this.memberId = memberId;
        this.context = context;
    }

    public void setMemberId(String memberId) {
        this.memberId = memberId;
    }

    private boolean isDisney = false;

    public void notifyDataSetChanged(List<TypeListBean> typeList, Boolean disney) {
        this.typeList = typeList;
        if (typeList != null) {

            ticketOrderDetailMap.clear();
            for (int i = 0; i < typeList.size(); i++) {
                ticketOrderDetailMap.put(i, createOrderDetail(typeList.get(i)));
            }
        }
        if (disney != null) {
            isDisney = disney;
        }

        notifyDataSetChanged();
    }


    /**
     * 价格变化接口
     * author Administrator
     * time 2016/6/29 17:31
     */
    public void setOnPriceChanged(OnPriceChanged onPriceChanged) {
        this.onPriceChanged = onPriceChanged;
    }

    @Override
    public int getCount() {
        if (typeList == null) {
            return 0;
        } else {
            return typeList.size();
        }

    }

    @Override
    public Object getItem(int position) {
        return null;
    }

    @Override
    public long getItemId(int position) {
        return 0;
    }

    @Override
    public View getView(final int position, View convertView, ViewGroup parent) {
        final ViewHold hold;
        TypeListBean bean = typeList.get(position);
        final EventPriceBean priceBean = getEventPriceBeanBymemId(typeList.get(position).getEventPrice());
        convertView = layoutInflater.inflate(R.layout.item_activities_ticket_select, parent, false);
        hold = new ViewHold(convertView);
        if (priceBean != null) {
            //设置票型
            StringUtils.setText(hold.type, bean.getLabelContent());
            //根据会员等级设置票价
//            DecimalFormat df = new DecimalFormat("#.00");
//            String p = df.format(priceBean.getPrice());

            StringUtils.setText(hold.price, DecimalFormatTool.getPaidMoneyString(priceBean.getPrice()) + "元");
            //专为迪士尼做的修改  17/6/8
            if (isDisney) {
                hold.price.setVisibility(View.GONE);
                hold.type.setMaxWidth(DensityUtil.dip2px(context, 250));
            }

            hold.add.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {

                    int num = ticketOrderDetailMap.get(position).getEventNum();
                    //判断是否超过当前库存
                    if (num >= Integer.valueOf(priceBean.getLimitNum())) {
                        T.show(context, "已达到购买限制张数", Toast.LENGTH_SHORT);
                        return;
                    }
                    if (num >= typeList.get(position).getStockNum()) {
                        T.show(context, "已达库存数量", Toast.LENGTH_SHORT);
                        return;
                    }

                    num += 1;
                    ticketOrderDetailMap.get(position).setEventNum(num);
                    onPriceChanged.onPrice(caculateTotalMoney());
                    onPriceChanged.onSelectedTicket(createTicketOrderLsitDetail());
                    StringUtils.setText(hold.num, num + "");
                }
            });
            hold.reduce.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    int num = ticketOrderDetailMap.get(position).getEventNum();
                    if (num == 0) {
                        handler.sendEmptyMessage(0);
                        return;//数量不能小于0，
                    }
                    num -= 1;
                    ticketOrderDetailMap.get(position).setEventNum(num);
                    onPriceChanged.onPrice(caculateTotalMoney());
                    onPriceChanged.onSelectedTicket(createTicketOrderLsitDetail());
                    StringUtils.setText(hold.num, num + "");
                }
            });

            L.e("TicketsAdapter-->" + "getView-->" + bean.toString());
            if (bean.getStockNum() == null || (int) bean.getStockNum() == 0) {
                hold.reduce.setImageResource(R.drawable.jo_select_pay_no);
                hold.add.setImageResource(R.drawable.jo_select_pay_no);
                hold.reduce.setClickable(false);
                hold.add.setClickable(false);
            }
        }


        return convertView;
    }


    private class ViewHold {
        TextView type;
        TextView price;
        TextView num;
        ImageView add;
        ImageView reduce;

        public ViewHold(View view) {
            type = (TextView) view.findViewById(R.id.textView4);
            price = (TextView) view.findViewById(R.id.tv_price);
            add = (ImageView) view.findViewById(R.id.iv_add);
            reduce = (ImageView) view.findViewById(R.id.iv_reduce);
            num = (TextView) view.findViewById(R.id.tv_number);

        }


    }

    /**
     * 价格改变接口
     * author Administrator
     * time 2016/6/29 17:27
     */
    public interface OnPriceChanged {
        public void onPrice(double price);

        public void onSelectedTicket(List<TicketOrderDetail> ts);
    }


    /**
     * 计算四个会员等级，挑选出适应当前用户等级的价格
     * <p/>
     * 这里的传入的memberId 可能为空，这时候为普通会员
     *
     * @return
     */
    private EventPriceBean getEventPriceBeanBymemId(List<EventPriceBean> beans) {
        double price = 0;
        EventPriceBean b = null;
        if (StringUtils.isEmpty(memberId)) {
            L.e("TicketsAdapter-->" + "memberId-->" + "null memberId");
            for (EventPriceBean bean : beans) {
                String m = bean.getMemberId();

            }

        } else {
            for (EventPriceBean bean : beans) {

                if (memberId.equals(bean.getMemberId())) {
                    b = bean;
                    break;
                } else {
                    b = bean;

                }


            }

        }


        return b;
    }


    /**
     * 计算四个会员等级对应的价格
     *
     * @param bean
     * @return
     */
    private double getPriceBymemId(TypeListBean bean) {
        double price = 0;
        if (StringUtils.isEmpty(memberId)) {
            L.e("TicketsAdapter-->" + "memberId-->" + "null memberId");
            throw new IllegalArgumentException("memberId can not be null");
        }


        if (price == 0) {
            //memberId 没有匹配价格
            throw new IllegalArgumentException("memberId can not match price");
        }
        return price;
    }


    /**
     * 计算总金额
     *
     * @return
     */
    private double caculateTotalMoney() {
        double money = 0;


        Set<Integer> keys = ticketOrderDetailMap.keySet();

        Iterator<Integer> it = keys.iterator();
        while (it.hasNext()) {
            TicketOrderDetail oD = ticketOrderDetailMap.get(it.next());
            money += Double.valueOf(oD.getEventPrice()) * oD.getEventNum();
        }

        return money;
    }

    /**
     * 创建选中票的集合
     *
     * @return
     */
    private List<TicketOrderDetail> createTicketOrderLsitDetail() {
        List<TicketOrderDetail> tdList = new ArrayList<>();
        Set<Integer> keys = ticketOrderDetailMap.keySet();

        Iterator<Integer> it = keys.iterator();
        while (it.hasNext()) {
            TicketOrderDetail oD = ticketOrderDetailMap.get(it.next());
            if (oD.getEventNum() != 0) {
                tdList.add(oD);
            }
        }
        return tdList;
    }

    /**
     * 创建一个新的价格bean
     *
     * @return
     */
    private TicketOrderDetail createOrderDetail(TypeListBean type) {
        TicketOrderDetail orderDetail = new TicketOrderDetail();
        EventPriceBean priceBean = getEventPriceBeanBymemId(type.getEventPrice());

        if (priceBean != null) {
            orderDetail.setStockId(type.getStockId());
            orderDetail.setEventNum(0);
            orderDetail.setEventPrice(priceBean.getPrice());
            orderDetail.setEventTypeId(type.getTypeLabelId());
            orderDetail.setTypeLabelContent(type.getLabelContent());
            return orderDetail;
        } else {
            return null;
        }


    }


}
